<?php
namespace Framework;

use App\Controllers\ErrorController;
use Framework\Middleware\Authorise;

class Router{
    protected $routes=[];
    private function registerRoute($method,$uri,$action,$middleware = []){
        
        list($controller, $controllerMethod) = explode('@', $action);
        // inspect($controllerMethod);

        $this->routes[]=[
            'method'=>$method,
            'uri'=>$uri,
            'controller'=>$controller,
            'controllerMethod'=>$controllerMethod,
            'middleware'=>  $middleware
        ];
    }

    public function addGet($uri,$controller,$middleware =[]){
        $this->registerRoute('GET',$uri,$controller,$middleware);
    }

    public function addPost($uri,$controller,$middleware =[]){
        $this->registerRoute('POST',$uri,$controller,$middleware);
    }

    public function addPut($uri,$controller,$middleware =[]){
        $this->registerRoute('PUT',$uri,$controller,$middleware);
    }

    public function addDelete($uri,$controller,$middleware =[]){
        $this->registerRoute('DELETE',$uri,$controller,$middleware);
    }

 
    public function error($httpCode = 404)
    {
        http_response_code($httpCode);
        loadView("error/{$httpCode}");
        exit;
    }

    
    public function route($uri)
{
    $requestMethod = $_SERVER['REQUEST_METHOD'];
    //检查POST 请求钟的特殊字段_method
    if($requestMethod==='POST'&& isset($_POST['_method'])){
        //重写请求方法
        $requestMethod = strtoupper($_POST['_method']);
    }

    // 拆分当前 URI
    $uriSegments = explode("/", trim($uri, '/'));

    foreach ($this->routes as $route) {

        // 拆分路由 URI
        $routeSegments = explode("/", trim($route['uri'], '/'));

        $match = false;

        // 检查拆分后的字符串片段数量是否匹配
        if (count($uriSegments) === count($routeSegments) && strtoupper($route['method'] == $requestMethod)) {
            $params = [];

            $match = true;

            for ($i = 0; $i < count($uriSegments); $i++) {
                // 如果有 URI 不匹配或者参数不存在
                if ($routeSegments[$i] !== $uriSegments[$i] && !preg_match('/\{(.+?)\}/', $routeSegments[$i])) {
                    $match = false;
                    break;
                }
                // 检查并且提取参数
                if (preg_match('/\{(.+?)\}/', $routeSegments[$i], $matches)) {
                    $params[$matches[1]] = $uriSegments[$i];
                }
            }
        }
        if ($match) {
                foreach($route['middleware'] as $middleware){
                    (new Authorise())->handle($middleware);
                }


            $controller = "App\\Controllers\\" . $route['controller'];
            $controllerMethod = $route['controllerMethod'];

            // 实例化控制器和调用控制器方法
            $controllerInstance = new $controller();
            $controllerInstance->$controllerMethod($params);
            return;
        }
    }
    // 如果没有匹配的路由，调用错误处理
    ErrorController::notFound();
}

    
}